import Modal from "antd-mobile/es/modal";
import Icon from "antd-mobile/es/icon";
import List from "antd-mobile/es/list";
import ActivityIndicator from "antd-mobile/es/activity-indicator";
import "antd-mobile/es/activity-indicator/style/css";

import React, { useState, useCallback, useRef } from 'react';
import { connect } from 'dva';
import { TeamOutlined, UserOutlined, LoadingOutlined } from '@ant-design/icons';
import TextView from '@alife/gcc-form-antd-mobile/es/components//TextView';
import SelectPersionList from 'components/formily/components/SelectPersionList';

import styles from './PhonePersonPicker.less';

const { Item } = List;

const dumpOrgCode = 'DUMP_CODE'; // 用于触发更新

const PhonePersonPicker = (props) => {

  const { customRender, dispatch, placeholder, params, value, defaultValue,onChange, itemProps, ...restProps } = props;

  const { disabled: propsDisabled } = restProps;
  const { disabled: itemDisabled } = itemProps || {};
  const disabled = Boolean(propsDisabled || itemDisabled);

  const { params: { multiple = false } = {} } = params || {};
  const mode = multiple ? 'multiple' : 'single';

  const [visible, setVisible] = useState(false);
  const [loadingRoot, setLoadingRoot] = useState(false);
  const [loadingOrgCode, setLoadingOrgCode] = useState(null);
  const dataSourceStackRef = useRef([[]]);
  const dataLength = dataSourceStackRef.current.length;
  const dataSource = dataSourceStackRef.current[dataLength-1];

  // value can be either undefined or { label, value } or [{ label, value }]
  const _value = value || defaultValue;

  const onShow = () => {
    if (!disabled) {
      dataSourceStackRef.current = [dataSourceStackRef.current[0]];
      if (dataSourceStackRef.current[0].length === 0) {
        getRootOrg().then(()=> setVisible(true));
        return;
      }
      setVisible(true);
    }
  };

  const onHide = () => { setVisible(false) };

  const handleOnChange = (currentItem, checked) => {
    const { code, displayName: label } = currentItem;
    const newValueItem = { value: code, label }; 
    if (currentItem.isLeaf) {
      // 添加
      if (checked) {
        if (mode === 'single') {
          onChange(newValueItem);
          onHide();
        } else {
          onChange((_value || []).filter(item => item.value !== code).concat(newValueItem));
        }
        return;
      }
      // 删除
      if (mode === 'single') {
        onChange(undefined);
      } else {
        onChange((_value || []).filter(item => item.value !== code));
      }
    } else {
      handleLoadData(currentItem);
    }
  };

  const getRootOrg = useCallback(() => {
    setLoadingRoot(true);
    return dispatch({
      type: 'usertreeSelect/getRootOrg', payload: {},
    }).then(({ errCode, datas }) => {
      if (errCode !== 0) {
        dataSourceStackRef.current = [[]];
      }
      dataSourceStackRef.current = [
        (Array.isArray(datas) ? datas : [datas]),
      ];
    }).finally(() => setLoadingRoot(false));
  }, [dispatch]);

  const handleLoadData = useCallback((item) => new Promise((resolve) => {
    const orgCode = item.code;
    const orgName = item.displayName;
    setLoadingOrgCode(orgCode);

    const isJustLoadOrg = false;
    if (item.children) {
      dataSourceStackRef.current.push(item.children);
      setTimeout(() => {
        setLoadingOrgCode(null);
        resolve();
      }, 200);
      return;
    }
    dispatch({
      type: 'usertreeSelect/getChildren', isJustLoadOrg, payload: { pageNo: 1, pageSize: 1000, orgCode, orgName },
    }).then(({ datas }) => {
      if (datas && datas.length >= 0) {
        item.children = datas;
        dataSourceStackRef.current.push(datas);
        resolve();
      }
      resolve();
    }).finally(() => setLoadingOrgCode(null));
  }), [dispatch]);

  const renderHeader = () => {
    return (
      <div className={styles.header}>
        <Icon type="cross" onClick={onHide} />
        <div>{placeholder}</div>
        <div className={styles.operation}>
          { dataSourceStackRef.current.length > 1 ? (
            <div
              onClick={() => {
                dataSourceStackRef.current.pop();
                setLoadingOrgCode(dumpOrgCode);
                setTimeout(()=>setLoadingOrgCode(null), 200);
              }}
            >
              返回上级
            </div>
          ) : null}
          <div onClick={onHide} style={{marginLeft: 8 }}>
            { mode === 'single' ? '' : '确定' }
          </div>
        </div>
      </div>
    );
  };

  const renderSelected  = () => {
    if (mode === 'multiple' && _value && _value.length) {
      return (
        <TextView value={_value} />
      );
    } else if (mode === 'single' && _value) {
      return  <TextView value={_value} />;
    } else {
      return (
        <div className="gcc-mobile-form-placeholder">
          { placeholder }
        </div>
      )
    }
  }


  const renderListItem = () => {
    let formatValue;
    if (mode === 'single') {
      formatValue = _value ? [_value] : _value;
    } else {
      formatValue = _value;
    }
    if (Array.isArray(dataSource) && dataSource.length) {
      return (
        <SelectPersionList
          {...restProps}
          disabled={disabled}
          dataSource={dataSource}
          value={formatValue}
          onChange={handleOnChange}
          getContent={(item) => {
            if (!item.isLeaf) {
              return (
                <div className={styles.listItem}>
                  <TeamOutlined style={{marginRight: 5}} />
                  {item.displayName}
                </div>
              );
            } else {
              return (
                <div className={styles.listItem}>
                  <UserOutlined style={{marginRight: 5}} />
                  {item.displayName}
                </div>
              );
            }
          }}
          renderExtra={(item) => {
            if (!item.isLeaf && loadingOrgCode === item.code) {
              // return <ActivityIndicator animating />;
              return <LoadingOutlined />;
            }
            return null;
          }}
        />
      );
    } else {
      return <div style={{padding: 12}}>暂无数据</div>;
    }
  }

  const result = renderSelected();

  return (
    <>
      { disabled ? result : (
        customRender ? customRender(_value, onShow, result) : (
          <Item arrow="horizontal" onClick={onShow}>
            { result }
          </Item>
      ))}
      <ActivityIndicator
        toast
        text="加载中"
        animating={loadingRoot}
      />
      <Modal
        popup
        visible={visible}
        onClose={onHide}
        animationType="slide-up"
      >
        <List
          renderHeader={renderHeader()}
          className="popup-list"
        >
          {renderListItem()}
        </List>
      </Modal>
    </>
  );
};


PhonePersonPicker.defaultProps = {
  placeholder: '请选择',
};
export default connect()(PhonePersonPicker);
